<template>
  <div class="container">
    <!-- 搜索区域 -->
    <div class="search-area">
      <el-input
          v-model="username"
          placeholder="请输入需要查询的用户名"
          class="search-input"
          clearable
          @keyup.enter="paging(1)">
      </el-input>
      <el-button type="primary" @click="paging(1)">查询</el-button>

      <!-- 添加管理员按钮 -->
      <el-button type="success" @click="openAddDialog">添加管理员</el-button>
    </div>

    <!-- 用户表格 -->
    <el-table :data="page.list" style="width: 100%" border>
      <el-table-column prop="id" label="序号"  align="center"></el-table-column>
      <el-table-column prop="name" label="姓名"  align="center"></el-table-column>
      <el-table-column prop="username" label="用户名"  align="center"></el-table-column>
      <el-table-column  label="身份"  align="center">
        <template v-slot="scope">
          {{scope.row.permission == 0 ?'顶级系统管理员' : scope.row.permission == 1 ?'普通系统管理员' : scope.row.permission == 2 ?'医院管理员' :
            scope.row.permission == 3 ?'取号缴费工作者' : scope.row.permission == 4 ?'发表检查报告工作者' : "-"}}
        </template>
      </el-table-column>
      <el-table-column label="关联医院"  align="center" v-if="showHidColumn">
        <template v-slot="scope">
          {{scope.row.hospital == null ?'-----' : scope.row.hospital.name}}
        </template>
      </el-table-column>

      <el-table-column label="操作" width="220" align="center" fixed="right">
        <template #default="scope">
          <el-button
              v-permission="'user:edit'"
              size="small"
              type="primary"
              @click="handleEdit(scope.row)">
            修改
          </el-button>
          <el-button
              v-permission="'user:delete'"
              size="small"
              type="danger"
              @click="handleDeleteUser(scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控件 -->
    <div class="pagination-area">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="paging"
          :current-page="page.pageNum"
          :page-sizes="[2, 3, 4, 5]"
          :page-size="page.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.total">
      </el-pagination>
    </div>

    <!-- 删除确认对话框 -->
    <el-dialog
        v-model="deleteDialogVisible"
        title="确认删除"
        width="30%"
        center>
      <span>确定要删除用户 <strong>{{ deleteUser?.username }}</strong> 吗？此操作不可撤销！</span>
      <template #footer>
        <el-button @click="deleteDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="confirmDelete">确定删除</el-button>
      </template>
    </el-dialog>

    <!-- 用户编辑对话框 -->
    <el-dialog
        v-model="editDialogVisible"
        :title="`编辑用户 - ${editUser?.username || ''}`"
        width="500px"
        center>
      <el-form :model="editUser" label-width="80px">
        <el-form-item label="用户名">
          <el-input v-model="editUser.username" autocomplete="off" />
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="editUser.name"  />
        </el-form-item>
        <el-form-item label="身份">
          <el-select v-model="editUser.permission" placeholder="请选择">
            <el-option label="顶级系统管理员" value="0" />
            <el-option label="普通系统管理员" value="1" />
            <el-option label="医院管理员" value="2" />
            <el-option label="取号缴费工作者" value="3" />
            <el-option label="发表检查报告工作者" value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="医院名" prop="hid" v-if="editUser.permission != 0 && editUser.permission != 1 && editUser.permission != null">
          <el-select v-model="editUser.hid" placeholder="请选择">
            <el-option v-for="item in HidList" :key="item.id"  :label="item.name" :value="item.id" >{{item.name}}</el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveEdit">保存</el-button>
      </template>
    </el-dialog>

    <!-- 添加管理员对话框 -->
    <el-dialog
        v-model="addDialogVisible"
        title="添加管理员"
        width="500px"
        center>
      <el-form :model="newAdmin" label-width="80px" :rules="addRules" ref="addForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="newAdmin.username" autocomplete="off" />
        </el-form-item>
        <el-form-item label="姓名" prop="password">
          <el-input v-model="newAdmin.name"  />
        </el-form-item>
        <el-form-item label="身份" prop="permission">
          <el-select v-model="newAdmin.permission" placeholder="请选择">
            <el-option label="顶级系统管理员" value="0" />
            <el-option label="普通系统管理员" value="1" />
            <el-option label="医院管理员" value="2" />
            <el-option label="取号缴费工作者" value="3" />
            <el-option label="发表检查报告工作者" value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="医院名" prop="hid" v-if="newAdmin.permission != 0 && newAdmin.permission != 1 && newAdmin.permission != null">
          <el-select v-model="newAdmin.hid" placeholder="请选择">
            <el-option v-for="item in HidList" :key="item.id"  :label="item.name" :value="item.id" >{{item.name}}</el-option>
          </el-select>
          <!--          <el-input v-model="newAdmin.hid" type="number" />-->
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveAdd">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>


import { ref, onMounted } from "vue";
import axios from "axios";
import { ElMessage } from 'element-plus';

const page=ref({
  pageNum: 1,
  pageSize: 5,
  total: 0,
  list: []
});
//搜索
const username=ref('');

//对话框

const newAdmin = ref({
  username: '',
  name: '',
  permission: '',
  hid: null
});


// 加载用户数据
const paging = async (curPage = 1) => {
    page.value.pageNum = curPage;
    const res = await axios.get('/admin/selAll', {
      params: {
        curPage: page.value.pageNum,
        pageSize: page.value.pageSize,
        username: username.value
      }
    });
    page.value = res.data;
};
// 更改每页大小
const handleSizeChange = (newSize) => {
  page.value.pageSize = newSize;
  paging(1);
};

const HidList=ref( [])
const getHidList = () => {
  axios.get('/hospital/selAllhospital').then(res=>{
    HidList.value=res.data.data
  })
}
// 初始化加载想让这个函数在页面加载时执行
onMounted(() => {
  paging();
  getHidList();
});
//增add=-========------------------------------------------------------------------------------------

//对话框状态

const addDialogVisible = ref(false);



// 表单验证规则
const addRules = ref({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在3到20个字符', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min:2, max: 20, message: '密码长度在6到20个字符', trigger: 'blur' }
  ],
  permission: [
    { required: true, message: '请选择权限', trigger: 'change' }
  ]
});

// 添加表单引用
const addForm = ref(null);

// 是否显示 hid 列
const showHidColumn = ref(true);

// 打开添加对话框
const openAddDialog = () => {
  // 重置表单数据
  newAdmin.value = {
    username: '',
    name: '',
    permission: '',
    hid: null
  };

  // 如果有验证错误，重置表单验证
  if (addForm.value) {
    addForm.value.resetFields();
  }

  addDialogVisible.value = true;
};// 保存添加的管理员 - 修改后的方法
const saveAdd = async () => {
  try {
    // 验证表单
    await addForm.value.validate();

    // 准备参数
    const params = {
      username: newAdmin.value.username,
      name: newAdmin.value.name,
      permission: newAdmin.value.permission,
    };

    // 添加 hid 参数（如果存在）
    if (newAdmin.value.hid !== null && newAdmin.value.hid !== undefined) {
      params.hid = newAdmin.value.hid;
    }

    // 发送GET请求到添加接口
    // const response = await axios.get('/admin/add', { params });
    const response=await axios.get('/admin/add',{params});
    console.log(response.data);
    // 处理响应 - 确保弹出成功提示
    if (response.data === 1) {
      ElMessage.success({
        message: '管理员添加成功',
        duration: 3000, // 3秒后自动关闭
        showClose: true, // 显示关闭按钮
      });
      addDialogVisible.value = false;
      paging(1); // 刷新数据
    } else {
      // 添加失败但HTTP状态码为200的情况
      ElMessage.error('添加失败，请重试');
    }
  } catch (error) {
    console.error('添加管理员失败:', error);

    // 更详细的错误处理
    if (error.response) {
      // 服务器返回了错误响应
      if (error.response.status === 400) {
        ElMessage.error('请求参数错误，请检查输入');
      } else {
        ElMessage.error(`服务器错误: ${error.response.status}`);
      }
    } else if (error.request) {
      // 请求已发送但无响应
      ElMessage.error('网络错误: 服务器无响应');
    } else {
      // 其他错误
      ElMessage.error(`请求错误: ${error.message}`);
    }
  }
};

//删===================================--------------------------------------------------------

// 删除用户
const deleteUser = ref(null);
const deleteDialogVisible = ref(false);


const handleDeleteUser = (row) => {
  deleteUser.value = row;
  deleteDialogVisible.value = true;
};

const confirmDelete = async () => {
  if (!deleteUser.value) return;

  try {
    await axios.get(`/admin/delById?id=${deleteUser.value.id}`);
    ElMessage.success('删除成功');

    // 智能分页处理
    if (page.value.list.length === 1 && page.value.pageNum > 1) {
      paging(page.value.pageNum - 1);
    } else {
      paging(page.value.pageNum);
    }
  } catch (error) {
    console.error('删除失败:', error);
    ElMessage.error('删除失败: ' + (error.response?.data?.message || error.message));
  } finally {
    deleteDialogVisible.value = false;
  }
};

//=========================--------------------------------------------------------------------------

// 编辑用户

const editDialogVisible = ref(false);


const editUser = ref({
  id: null,
  username: '',
  name: '',
  permission: '',
  hid: null
});
const handleEdit = (row) => {
  // 复制用户数据，避免直接引用
  editUser.value = { ...row };
  editDialogVisible.value = true;
};

// 修改后的保存方法
const saveEdit = async () => {
  if (!editUser.value.id) return;

  try {
    // 构建查询字符串参数
    const params = new URLSearchParams({
      id: editUser.value.id,
      username: editUser.value.username,
      name: editUser.value.name,
      permission: editUser.value.permission,
      hid: editUser.value.hid || ''
    }).toString();

    // 发送 GET 请求
    await axios.get(`/admin/update?${params}`);

    ElMessage.success('更新成功');
    editDialogVisible.value = false;
    paging(page.value.pageNum); // 刷新当前页
  } catch (error) {
    console.error('更新失败:', error);

    // 更详细的错误处理
    if (error.response) {
      // 服务器响应了错误状态码 (4xx, 5xx)
      ElMessage.error(`服务器错误: ${error.response.status} - ${error.response.data?.message || '未知错误'}`);
    } else if (error.request) {
      // 请求已发送但无响应
      ElMessage.error('网络错误: 服务器无响应');
    } else {
      // 其他错误
      ElMessage.error(`请求错误: ${error.message}`);
    }
  }
};


</script>
<style scoped>

.container {
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-area {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.search-input {
  width: 300px;
}

.pagination-area {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

</style>